(function(){

window.onload = function(){
    game.init();
}

var game = window.game = {
    width: 0,
    height: 0,

    asset: null,
    stage: null,
    ticker: null,
    state: null,
    score: 0,

    bg: null,
    ground: null,
    car: null,
    carOut: null,
    pole:null,
    inPole:null,
    outPole:null,
    monitor:null,
    QRcode:null,
    //游戏控件
    holdbacks: null,
    aircraft: null,
    homeBmImg: null,
    shell: null,
    shells: new Hilo.Container({id:"shells"}),
    missile: null,
    missiles: new Hilo.Container({id:"missiles"}),
    Bmissiles: new Hilo.Container({id:"Bmissiles"}),
    num: null,
	tank: null,     //坦克控件
	tankAtlas:null, //坦克动画集
    gameReadyScene: null,
    gameOverScene: null,
    ticker:null,
    //基本数据
    currentScore:null,		//当前分数控件
    statisticsScore:0,		//累计分数
    tankIsDead:false,		//坦克是血量未0
    tankBlood:3,			//坦克血量
    currentLevel:1,     	//当前关卡
   	//飞机boss
   	BOSS:null,          	//BOSS控件
    bossIsDead:false,		//BOSS是否死亡
    bossBlood:20,       	//BOSS血量
    BOSSAtlas:null, 	    //BOSS控件动画集
    BOSS_MS_Atlas:null, 	//BOSS导弹动画集
    MissileLoader:false,	//导弹装填中
    //粒子
    Missile_Particles:null,	//飞弹粒子
    //音效
    missileBomb:null,   //坦克碰撞 
    tankShooting:null,  //坦克射击
    missileFlight:null, //导弹飞行
    init: function(){
        this.asset = new game.Asset();
        this.asset.on('complete', function(e){
            this.asset.off('complete');
            this.initStage();
        }.bind(this));
        this.asset.load();
    },

    initStage: function(){
    	var winWidth = window.innerWidth || document.documentElement.clientWidth;
		var winHeight = window.innerHeight || document.documentElement.clientHeight;
        this.width = 720;
        this.height = 1080;
        this.scale = 0.5;

        //舞台
        this.stage = new Hilo.Stage({
            renderType:'canvas',
            width: this.width,
            height: this.height,
            scaleX: this.scale,
            scaleY: this.scale
        });
        this.stage.enableDOMEvent([Hilo.event.POINTER_START, Hilo.event.POINTER_MOVE, Hilo.event.POINTER_END]);
        document.body.appendChild(this.stage.canvas);

        //启动计时器
        this.ticker = new Hilo.Ticker(60);
        this.ticker.addTick(Hilo.Tween);
        this.ticker.addTick(this.stage);
        this.ticker.start();

        

        //舞台更新
        //this.stage.onUpdate = this.onUpdate.bind(this);

        //初始化
        this.initBackground();
      	this.initScenes();
//      this.initHoldbacks();
//      this.initBird();
	    this.initCurrentScore();
	    
//
//      //准备游戏
//      this.gameReady();
	//Hilo.Stage.prototype.showDrawRect();
    },

    initBackground: function(){
        //背景
        var bgWidth = this.width * this.scale;
        var bgHeight = this.height * this.scale;
        
        document.body.insertBefore(Hilo.createElement('div', {
            id: 'bg',
            style: {
                background: 'url(img/bg.jpg) no-repeat',
                backgroundSize: bgWidth + 'px, ' + bgHeight + 'px',
                position: 'absolute',
                width: bgWidth + 'px',
                height: bgHeight + 'px'
            }
        }), this.stage.canvas);
        
        //音效准备
        this.missileBomb=Hilo.WebSound.getAudio({src:this.asset.soundBomb,loop: false});
	    this.missileFlight=Hilo.WebSound.getAudio({src:this.asset.missileFlight,loop: false});
	    this.tankShooting=Hilo.WebSound.getAudio({src:this.asset.tankShooting,loop: false});
	    
        //背景
        this.homeBmImg= new Hilo.Container({
                x:0,
                y:0,
                width:this.asset.homeBmImg.width,
                height:this.asset.homeBmImg.height,
                style: {
	                //background: 'url('+this.asset.homeBmImg+') no-repeat',
	                backgroundSize: bgWidth + 'px, ' + bgHeight + 'px',
	                position: 'absolute',
	            }
            }).addTo(this.stage);
        this.homeBmImg.background = this.stage.renderer.context.createPattern(this.asset.homeBmImg, 'repeat-x');
        //设置地面的y轴坐标
        this.homeBmImg.y = this.height - this.homeBmImg.height;

        //移动地面
        Hilo.Tween.to(this.homeBmImg, {x:-this.asset.homeBmImg.width*0.6}, {duration:10000, loop:true});
        
        //      this.shell = new Hilo.ParticleSystem({
//          x:0,
//          y:0,
//          emitNum:1,
//          emitTime:2,
//          particle:{
//              frame:[
//                  [0, 0, 60, 90],
//                  //[20, 113, 20, 20],
//                  //[20, 120, 30, 30]
//              ],
//              
//              image:this.asset.shell,
//              life:100,
//              //alphaV:-.01,
//              //scaleV:-0.01,
//              //vx:300,
//              vy:-this.stage.height*0.2,
//              //axVar:200,
//              //ay:-this.stage.height,
//              //scale:1,
//              rotation:0,
//              //rotationV:1,
//              //pivotX:1,
//             	//pivotY:1
//             	onUpdate:function(){
//             		
//             		if(this.y<0){
//             			game.shell.removeChild(this);
//             		}else{
//             			this.y=this.y-5;
//             		}
//             		//碰撞检测
//		            for (var i = game.aircraft.children.length - 1; i >= 0; i--) {
//		            	if(game.aircraft.children[i].hitTestObject(this,false)){
//		            		game.aircraft.removeChildAt(i);
//		            		game.shell.removeChild(this);
//		            		game.statisticsScore=game.statisticsScore+2;
//		            		game.currentScore.setText(game.statisticsScore);
//		            	}else{
//		            		//console.log("2");
//		            		
//		            	}
//		            }
//		            //碰撞检测2
//		            for (var i = game.missiles.children.length - 1; i >= 0; i--) {
//		            	if(game.missiles.children[i].hitTestObject(this,false)){
//		            		game.missiles.removeChildAt(i);
//		            		game.shell.removeChild(this);
//		            		game.statisticsScore=game.statisticsScore+1;
//		            		game.currentScore.setText(game.statisticsScore);
//		            	}else{
//		            		//console.log("2");
//		            		
//		            	}
//		            }
//		            
//		        }                
//          }
//      });
//      this.stage.addChild(this.shell);
//      this.shell.start();
//飞机导弹
//      this.missile = new Hilo.ParticleSystem({
//          x:0,
//          y:0,
//          emitNum:1,
//          emitTime:5,
//          emitterX:0,
//          emitterY:0,
//          particle:{
//              frame:[
//                  [0, 0, 60, 90],
//              ],
//              image:this.asset.missile,
//              life:100,
//              vx:-100,
//              onUpdate:function(){
//             		
//             		if(this.y<0){
//             			game.missile.removeChild(this);
//             		}else{
//             			this.y=this.y+5;
//             		}
//             		//碰撞检测
//             		
//             		for (var i = game.missile.children.length - 1; i >= 0; i--) {
//		            	if(game.missile.children[i].hitTestObject(game.tank,false)){
//		            		game.missile.removeChildAt(i);
//		            		if(game.statisticsScore-1<=0){
//		            			game.currentScore.setText(0);
//		            		}else{
//		            			game.currentScore.setText(game.statisticsScore-1);
//		            		}
//		            		
//		            	}else{
//		            		//console.log("2");
//		            		
//		            	}
//		            }
//		        }
//          }
//      });
//      this.stage.addChild(this.missile);
//      this.missile.start();
        //二维码
        this.QRcode = new Hilo.Bitmap({
        	image: 'img/QRcode.png',
        	x:this.stage.width * 0.44,
        	y:this.stage.height * 0.44,
        	width:100,
        	height:100
        	//align:Hilo.align.TOP
        }).addTo(this.stage);
  },
//
    initCurrentScore: function(){
        //当前分数
        this.currentScore = new Hilo.BitmapText({
            id: 'score',
            glyphs: this.asset.numberGlyphs,
            text: this.statisticsScore
        }).addTo(this.stage);
        
        //设置当前分数的位置
        this.currentScore.x = this.width - this.currentScore.width >> 1;
        this.currentScore.y = 180;
    },
//
//  initBird: function(){
//      this.bird = new game.Bird({
//          id: 'bird',
//          atlas: this.asset.birdAtlas,
//          startX: 100,
//          startY: this.height >> 1,
//          groundY: this.ground.y - 12
//      }).addTo(this.stage, this.ground.depth - 1);
//  },
//
//  initHoldbacks: function(){
//      this.holdbacks = new game.Holdbacks({
//          id: 'holdbacks',
//          image: this.asset.holdback,
//          height: this.height,
//          startX: this.width * 2,
//          groundY: this.ground.y
//      }).addTo(this.stage, this.ground.depth - 1);
//  },

    initScenes: function(){
    	//坦克动画集
		this.tankAtlas = new Hilo.TextureAtlas({
            image: game.asset.tanks,
            width: 1064,
            height: 511,
            frames: {
	            frameWidth: 176,
	            frameHeight: 180,
	            numFrames: 17
            },
//          frames: [
//          	[0,0,175,155],
//          	[175+1,0,175,155],
//          	[175*2+1,0,175,155],
//          	[175*3+1,0,175,155],
//          	[175*4+1,0,175,155],
//          	[175*5+1,0,175,155]
//          ],
            sprites: {
                tanks: {from:0, to:4},
                tanksDie: {from:6, to:10},
                tanksAttack: {from:12, to:16},
                //fishDie: {from:4, to:4}
            }
       });
            
        //坦克外框
        var tankContainer = new Hilo.Container({
                x:this.stage.width * .05,
                y:this.stage.height*.85,
                height:10,
                width:this.stage.width * .9,
                background:"#f00",
                
            }).addTo(this.stage);
        //坦克
		this.tank =new Hilo.Sprite({
            frames: game.tankAtlas.getSprite('tanks'),
            x: tankContainer.x,
            y: tankContainer.y,
            interval: 300,
            timeBased: true,
            loop: true
        }).addTo(game.stage);
		
		//坦克移动
        Hilo.copy(this.tank, Hilo.drag);
        this.tank.startDrag([tankContainer.x, tankContainer.y, tankContainer.width - this.tank.width, tankContainer.height - this.tank.height]);
        
        this.tank.on("dragMove", function(e){
            //game.tank.goto(5, true);
            //console.log("dragStart", e.detail.x, e.detail.y);
            //game.tank.setFrames(game.tankAtlas.getSprite('tanks'),true,300);
        });
        this.tank.on("dragEnd", function(e){
           
            if(game.tankIsDead){return false;}
            game.tank.setFrames(game.tankAtlas.getSprite('tanksAttack'),true,300);
            //setTimeout(function(){game.tank.setFrames(game.tankAtlas.getSprite('tanks'),true,300);},1500);
            //添装导弹
        	game.shell = new Hilo.Bitmap({
	        	image: game.asset.shell,
	        	x:this.x+55,
	        	y:this.y-55,
	        	size:2
	        }).addTo(game.stage);
            //game.tankShooting.play();
	        //发射导弹
	        Hilo.Tween.to(game.shell, {y:-game.stage.height,rotationV:10}, {duration:5000, loop:false});
	        game.shells.addChild(game.shell);
	        game.shells.addTo(game.stage);
        });
        //坦克炮弹
        
        //BOSS动画集
		this.BOSSAtlas = new Hilo.TextureAtlas({
            image: game.asset.boss,
            width: 1137,
            height: 283,
            frames: {
	            frameWidth: 284,
	            frameHeight: 141,
	            numFrames: 8
            },
            sprites: {
                BOSS: {from:0, to:3},
                BOSSDead: {from:3, to:7}
            }
       });
       
       //BOSS导弹动画集
		this.BOSS_MS_Atlas = new Hilo.TextureAtlas({
            image: game.asset.bossMissile,
            width: 625,
            height: 307,
            frames: {
	            frameWidth: 34.5,
	            frameHeight: 145,
	            numFrames: 32
            },
            sprites: {
                fish: {from:0, to:17},
                fishDie: {from:20, to:31}
            }
       });
       
       //BOSS
       this.BOSS =new Hilo.Sprite({
            frames: game.BOSSAtlas.getSprite('BOSS'),
            x: 0,
            y: game.stage.height*.5,
            interval: 300,
            timeBased: true,
            loop: true,
            size:3,
            onUpdate: function(){
                if(game.bossIsDead){
                	this.x = -this.width;
                	return false;
                }
                
                
	            for (var i = game.Bmissiles.children.length - 1; i >= 0; i--) {
	            	if(game.Bmissiles.children[i].y > game.height){
	            		game.Bmissiles.removeChildAt(i);
	            	}else{
	            		//console.log("2");
	            		
	            	}
	            }
                
           		this.size=1;
           		if(this.size==undefined){
           			this.size=3;
           		}
           		
                if(parseInt(Math.random()*100)==0 && this.size>0){
                	game.BOSS.goto(3, true);
                	game.MissileLoader=true;
                	//减导弹库存-
                	this.size=this.size-1;
                	//反坦克集束炸弹填装完毕！
                	var missile = new Hilo.Sprite({
        				frames: game.BOSS_MS_Atlas.getSprite('fish'),
			        	x:this.x+this.width*.5,
			        	y:this.y-20,
			        	interval: 100,
					    timeBased: true,
					    loop: false,
			        }).addTo(game.stage);
			        //目标未锁定，直线发射导弹！
			        //game.missileFlight.play();
			        Hilo.Tween.to(missile, {y:game.height}, {duration:1500, loop:false,onComplete:function(){
				       	game.BOSS.goto(3, false);
				        game.MissileLoader=false;
			        }});
			        
			        game.Bmissiles.addChild(missile);
			        game.Bmissiles.addTo(game.stage);
                }else if(this.x > game.stage.width - this.pivotX){
                    this.x = 0;
                }else if(!game.MissileLoader){
                    this.x += 3;
                    Hilo.Tween.to(this, {y:game.stage.height*.5+parseInt(Math.random()*200)}, {duration:1000, loop:false});
                    //this.y = game.stage.height*.5+parseInt(Math.random()*100);
                }
            }
        }).addTo(game.stage);
       this.Missile_Particles = new Hilo.ParticleSystem({
                x:this.stage.width*.5,
                y:this.stage.height*.5,
                emitNum:2,
                emitTime:1,
                particle:{
                    frame:[
                        [0, 0, 30, 32],
                        [0, 0, 30, 32]
                    ],
                    image:this.asset.missileParticles,
                    life:22,
                    //alphaV:-.01,
                    vxVar:300,
                    vyVar:300,
                    axVar:200,
                    ayVar:200,
                      scale:.5,
                      rotationVar:100,
                      rotationVVar:10,
                      pivotX:.5,
                      pivotY:1,
//                  onUpdate:function(){
//                  	this.rotation=90;
//                  	this.y+=1;
//                  	this.x+=1;
//                  	if(this.size==undefined){
//                  		this.size=0;
//                  		this.rotationVVar=4;
//                  		Hilo.Tween.to(this, {y:game.stage.height,rotation:90}, {duration:1500, loop:false});
//                  	}
//                  }
                }
            });
    this.stage.addChild(this.Missile_Particles);
    this.Missile_Particles.start();
		
        //飞机
        this.aircraft = new Hilo.ParticleSystem({
            x:0,
            y:0,
            emitNum:1,
            emitTime:5,
            emitterX:600,
            particle:{
                frame:[
                    [0, 0, 180,80],
                    [0, 0, 180, 120],
                    [0, 0, 180, 80],
                ],
                image:this.asset.aircraft,
                life:100,
                vx:-100,
                size:3,
                onUpdate:function(){
               		if(game.tankIsDead){return false;}
               		//this.size=1;
               		if(this.size==undefined){
               			this.size=3;
               		}
               		if(this.x<0-this.width){
               			game.aircraft.removeChild(this);
               		}else{
               			this.x=this.x-5;
               		}
               		//飞机导弹
	                //飞导弹几率
	                if(parseInt(Math.random()*30)==0 && this.size>0){
	                	//减导弹库存-
	                	this.size=this.size-1;
	                	//反坦克集束炸弹填装完毕！
	                	game.missile = new Hilo.Bitmap({
				        	image: game.asset.missile,
				        	x:this.x,
				        	y:this.y-20,
				        }).addTo(game.stage);
				        //目标未锁定，直线发射导弹！
				        //game.missileFlight.play();
				        Hilo.Tween.to(game.missile, {y:game.stage.height+this.height,rotation:90}, {duration:1500, loop:false});
				        game.missiles.addChild(game.missile);
				        game.missiles.addTo(game.stage);
	                }
		        }
            }
        });
        this.stage.addChild(this.aircraft);
        this.aircraft.start();
        
        
        //发射计算
        this.ticker.addTick({
            tick:function(){
            	//子弹位置
                //game.shell.emitterX = game.tank.x+game.tank.width*.4;
                //game.shell.emitterY = game.tank.y-20;
                
                //飞机位置
                //game.aircraft.emitterY = Math.random()*100;
                //碰撞检测 飞机和炮弹
//	            for (var i = game.aircraft.children.length - 1; i >= 0; i--) {
//	            	for (var j = game.shells.children.length - 1; j >= 0; j--) {
//	            		if(game.aircraft.children[i].hitTestObject(game.shells.children[j],false)){
//		            		game.aircraft.removeChildAt(i);
//		            		game.shells.removeChildAt(j);
//		            		game.statisticsScore=game.statisticsScore+2;
//		            		game.currentScore.setText(game.statisticsScore);
//		            	}else{
//		            		//console.log("2");
//		            		
//		            	}
//	            	}
//	            }
	            //碰撞检测 导弹和炮弹
	            Hilo.WebSound.enableAudio();
	            if(!game.bossIsDead &&game.bossBlood<=0){
	            	game.BOSS.setFrames(game.BOSSAtlas.getSprite('BOSSDead'),false,300);
	            	setTimeout(function(){game.bossIsDead=true;},1500);//
	            }
	            //判断目标是否以被摧毁
	            if(!game.tankIsDead&&game.tankBlood<=0){
            		game.tankIsDead=true;
            		
            		game.tank.setFrames(game.tankAtlas.getSprite('tanksDie'),true,500);
            		setTimeout(function(){game.tank.goto(5, true);},2500);
            		game.missileBomb.play();
        		}else if(!game.tankIsDead){
		            //碰撞检测【炮弹】
		            for (var i = game.shells.children.length - 1; i >= 0; i--) {
		            	var isZha=false;
		            	//空对地反坦克突击地面目强击机
		            	for (var j = game.aircraft.children.length - 1; j >= 0; j--) {
		            		if(game.shells.children[i].hitTestObject(game.aircraft.children[j],false)){
		            			//game.aircraft.removeChildAt(j);
		            			game.aircraft.children[j].setImage(game.asset.aircraft,[0, 0, 100, 100]);
		            			game.aircraft.stop();
			            		game.shells.removeChildAt(i);
			            		game.statisticsScore=game.statisticsScore+2;
			            		game.currentScore.setText(game.statisticsScore);
			            		isZha=true;
			            	}
		            	}
		            	//反坦克集束炸弹和空地导弹
		            	for (var g = game.missiles.children.length - 1; g >= 0; g--) {
		            		if(game.shells.children[i].hitTestObject(game.missiles.children[g],false)){
		            			game.missiles.removeChildAt(g);
			            		game.statisticsScore=game.statisticsScore+1;
			            		game.currentScore.setText(game.statisticsScore);
			            		
			            	}
		            	}
		            	//攻击BOSS
		            	if(game.shells.children[i].hitTestObject(game.BOSS,false)){
		            		isZha=true;
		            		game.statisticsScore=game.statisticsScore+2;
		            		game.bossBlood=game.bossBlood-1;
			            	game.currentScore.setText(game.statisticsScore);
		            	}
		            	if(isZha){
		            		game.shells.removeChildAt(i);
		            	}else if(game.shells.children[i].y<0){
		            		game.shells.removeChildAt(i);
		            	}
		            	
		            }
	            
	            	for (var g = game.missiles.children.length - 1; g >= 0; g--) {
	            		if(game.tank.hitTestObject(game.missiles.children[g],false)){
	            			//debugger
	            			game.missiles.removeChildAt(g);
            				game.tankBlood=game.tankBlood-1;
            				game.tank.goto(5, false);
            				
		            	}
	            	}
	            }
	            
            }
            
      });
//      //准备场景
//      this.gameReadyScene = new game.ReadyScene({
//          width: this.width,
//          height: this.height,
//          image: this.asset.ready
//      }).addTo(this.stage);
//
//      //结束场景
//      this.gameOverScene = new game.OverScene({
//          width: this.width,
//          height: this.height,
//          image: this.asset.over,
//          numberGlyphs: this.asset.numberGlyphs,
//          visible: false
//      }).addTo(this.stage);
//
//      //绑定开始按钮事件
//      this.gameOverScene.getChildById('start').on(Hilo.event.POINTER_START, function(e){
//          e._stopped = true;
//          this.gameOverScene.visible = false;
//          this.gameReady();
//      }.bind(this));
//  },
//
//  onUserInput: function(e){
//      if(this.state !== 'over'){
//          //启动游戏场景
//          if(this.state !== 'playing') this.gameStart();
//          //控制小鸟往上飞
//          this.bird.startFly();
//      }
//  },
//
//  onUpdate: function(delta){
//      if(this.state === 'ready'){
//          return;
//      }
//
//      if(this.bird.isDead){
//          this.gameOver();
//      }else{
//          this.currentScore.setText(this.calcScore());
//          //碰撞检测
//          if(this.holdbacks.checkCollision(this.bird)){
//              this.gameOver();
//          }
//      }
    },
    //初始化数据
    gameReady: function(){
        this.state = 'ready';
        //分数重置
        this.score = 0;
        this.currentScore.visible = true;
        this.currentScore.setText(this.score);
        
        this.gameReadyScene.visible = true;
        //清空飞机 炮弹 导弹 BOSS导弹
        this.shells=new Hilo.Container({id:"shells"})
		this.missiles=new Hilo.Container({id:"missiles"}),
		this.Bmissiles=new Hilo.Container({id:"Bmissiles"});
        //坦克准备
        //this.holdbacks.reset();
        //BOOS准备
        //this.bird.getReady();
    },
	//初始化控件
    gameStart: function(){
        this.state = 'playing';
        this.gameReadyScene.visible = false;
        this.holdbacks.startMove();
    },
//
    gameOver: function(){
        if(this.state !== 'over'){
            //设置当前状态为结束over
            this.state = 'over';
            //停止障碍的移动
            this.holdbacks.stopMove();
            //小鸟跳转到第一帧并暂停
            this.bird.goto(0, true);
            //隐藏屏幕中间显示的分数
            this.currentScore.visible = false;
            //显示结束场景
            this.gameOverScene.show(this.calcScore(), this.saveBestScore());
        }
    },
	//
    calcScore: function(){
        var count = this.holdbacks.calcPassThrough(this.bird.x);
        return this.score = count;
    },
    //保存分数
    saveBestScore: function(){
        var score = this.score, best = 0;
        if(Hilo.browser.supportStorage){
            best = parseInt(localStorage.getItem('hilo-flappy-best-score')) || 0;
        }
        if(score > best){
            best = score;
            localStorage.setItem('hilo-flappy-best-score', score);
        }
        return best;
  }
};

})();